package com.example.whm;



import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.text.format.DateUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;
import com.example.whm.loader.asytask;
import com.example.whm.model.Item;
import com.example.whm.model.ZaoDian;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class TwoFragmentItem extends Fragment  implements OnItemClickListener,LoaderCallbacks<List<Item>>{

	private AQuery aq;
	private AQuery aq2;
	
	private String topic;
	boolean tag=false;
	List<ZaoDian> data;
	List<ZaoDian> list=new ArrayList<ZaoDian>();
    String topic_cur;
	int pos_cur;
	Bundle bun;
	int type;
	String query="";
	adapter adp;
	PullToRefreshGridView mPullRefreshListView;
	
	
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        
    	View view = inflater.inflate(R.layout.two_layout_fragment, container, false);        	
		System.out.println("onCreateView");
		//System.out.println("getArguments()==null   ->"+(getArguments()==null));
		//System.out.println("savedInstanceState==null   ->"+(savedInstanceState==null));
    	if (getArguments()!=null) {
    		bun=getArguments();
    		topic=getArguments().getString("topic");
    		type=getArguments().getInt("type");
		//	System.out.println("getArguments() topic=="+getArguments().getString("topic"));;
		//	System.out.println("getArguments() pos=="+getArguments().getInt("pos"));;
		}
    	aq = new AQuery(getActivity(), view);
    	aq2 = new AQuery(getActivity());
    	aq.find(R.id.progress).visible();
    	
    	//aq.id(R.id.two_layout_fragment_listview).itemClicked(this);
    	
    	mPullRefreshListView = (PullToRefreshGridView)view.findViewById(R.id.two_layout_fragment_listview);

		// Set a listener to be invoked when the list should be refreshed.
    	
    	
    	
    	
    	
    	mPullRefreshListView.setOnRefreshListener(new OnRefreshListener2<GridView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<GridView> refreshView) {
				// TODO Auto-generated method stub
				String label = DateUtils.formatDateTime(getActivity().getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				query("refresh");				
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<GridView> refreshView) {
				// TODO Auto-generated method stub
				String label = DateUtils.formatDateTime(getActivity().getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				query("loading");
				/*refreshView.getLoadingLayoutProxy().setPullLabel("loading");
				refreshView.getLoadingLayoutProxy().setRefreshingLabel("loading");
				refreshView.getLoadingLayoutProxy().setReleaseLabel("loading");*/
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
			}
		});
		/*mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String label = DateUtils.formatDateTime(getActivity().getApplicationContext(), System.currentTimeMillis(),
						DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

				// Update the LastUpdatedLabel
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

				// Do work to refresh the list here.
				//new GetDataTask().execute();
			}
		});*/

		// Add an end-of-list listener
	/*	mPullRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

			@Override
			public void onLastItemVisible() {
				Toast.makeText(getActivity(), "End of List!", Toast.LENGTH_SHORT).show();
			}
			
			
			
		});*/
    	mPullRefreshListView.setOnItemClickListener(TwoFragmentItem.this); 
    	//Log.i("TwoFragmentItem", "tonCreateView---------------i="+i);
    	//Log.i("TwoFragmentItem", "---------------onCreateView");
    	//Log.i("TwoFragmentItem", "---------------onCreateView savedInstanceState="+(savedInstanceState==null));
    	//Log.i("TwoFragmentItem", "---------------onCreateView getArguments()="+(getArguments().getInt("pos")));
		return view;
		
    }
    
    @Override
	public void onActivityCreated(Bundle savedInstanceState){

    	//System.out.println("onActivityCreated");
    	super.onActivityCreated(savedInstanceState);
    	Bundle b=new Bundle();
    	
    	
    	  init();
    	//	getLoaderManager().initLoader(0, bun, this);
    	 /*  if (index==0) {
    	
		}*/
    		
    	
    	
    }

    
    
    public void query(String query){
    	long q=new Date().getTime();
    	String g = null; 
    	this.query=query;
    	if (!list.isEmpty()) {
    		if (query.equals("refresh")) {
    			q=list.get(0).getTimemils();
    			g="r";
    			
			}
    		if (query.equals("loading")) {
    			q=list.get(list.size()-1).getTimemils();
    			g="n";
    			
    		}
    		
			
		}
    	String url = "http://"+Whm_app.api_url+":9000/api/list_zaodian?t="+type+"&g="+g+"&q="+q;
    	//String url = "http://219.239.236.77/statuses/puzzles";
      	aq.ajax(url, String.class, this, "parsedata");
    }
 
    
    public void init(){
    	
    	
    	//Log.i("TwoFragmentItem", "---------------init");
    	if (aq==null||tag) return;
    	tag=true;
    	String url = "http://"+Whm_app.api_url+":9000/api/list_zaodian?t="+type;
    	//String url = "http://219.239.236.77/statuses/puzzles";
      	aq.ajax(url, String.class, this, "parsedata");
    	
    	//bun.putString("url", "http://219.239.236.77/statuses/puzzles"); 
    	//getLoaderManager().initLoader(0, bun, this);
    
    }
    public void parsedata(String url, String s, AjaxStatus status){
    	System.out.println(status.getCode());
    	if(s != null){
    		ui(s);
    	}
    	
    }

 public void ui(String str){
	 final String s=str;
	 new Thread( new Runnable() {
         @Override
		public void run() {
        	// String s1= JSON.parseObject(s).getString("users");
        	 String s1= JSON.parseObject(s).getString("result");
     		//System.out.println("s1============"+s1);
        	 
     		 if (query.equals("refresh")) {
     			list.addAll(0,JSON.parseArray(s1, ZaoDian.class));
			}else if(query.equals("loading")||query.equals("")){
				list.addAll(JSON.parseArray(s1, ZaoDian.class));
			}
     		 
     		 getActivity().runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						//Toast.makeText(getActivity(), "type="+type+",list.size="+list.size(), 1000).show(); 
			     	//	Toast.makeText(getActivity(), "data.size="+data.size(), 1000).show(); 
						aq.find(R.id.progress).gone();
					    
						
						//System.out.println("query="+query);
						if (query.equals("")) {
							adp=new adapter(list);
							mPullRefreshListView.setMode(Mode.BOTH);
							mPullRefreshListView.setAdapter(adp);
							
						}else{
							
							adp.notifyDataSetChanged();
							mPullRefreshListView.onRefreshComplete();
						}
						
						
						
					}
				});
          }
 }).start();
 }   
    
    
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
	// TODO Auto-generated method stub
	ZaoDian i=(ZaoDian) arg0.getItemAtPosition(arg2);
	 Intent inte=new Intent(getActivity(), EntityDetail.class);
	  if (inte.getExtras()!=null) {
		  inte.getExtras().putString("id", i.getId());
	}else{
		Bundle b=new Bundle();
		b.putString("id", i.getId());
		inte.putExtras(b);
	}
	  startActivity(inte);
	 
	
}




class adapter extends BaseAdapter{

	
	List<ZaoDian> list;
	public adapter() {
		super();
		// TODO Auto-generated constructor stub
	}
   
	
	public adapter(List<ZaoDian> list) {
		super();
		this.list = list;
	}


	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return list.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		// TODO Auto-generated method stub
		if(arg1 == null){
			arg1 = aq.inflate(arg1, R.layout.two_layout_fragment_item, arg2);
		}
		
		ZaoDian i = (ZaoDian) getItem(arg0);
		
		AQuery aq = aq2.recycle(arg1);
		
		String tbUrl = i.getPre_pic().replace("localhost", Whm_app.api_url);
		aq.id(R.id.two_f_i_text).text(i.getName());
		aq.id(R.id.two_f_i_price).text("¥"+String.valueOf(i.getPrice()));
		//aq.id(R.id.two_f_i_tatal).text(String.valueOf(i.getNum()*i.getEntity().getPrice()));
		//String tbUrl = i.getImg_url();
	
		//System.out.println("tbUrl=================="+tbUrl);
		//Bitmap placeholder = aq.getCachedImage(R.drawable.image_ph);
		//Bitmap bit=aq.getCachedImage(R.drawable.ic_launcher);
		if(aq.shouldDelay(arg0, arg1, arg2, tbUrl)){
					
			//aq.id(R.id.two_f_i_image).image(bit);
			aq.id(R.id.two_f_i_image).clear();
			
		}else{
			
			//aq.id(R.id.two_f_i_image).image(tbUrl, true, true, 200, R.drawable.ic_launcher, bit, 0, 0);
			
			aq.id(R.id.two_f_i_image).image(tbUrl, true, true, 200, R.drawable.ic_launcher, null, 0, 0);
		}
		//aq.id(R.id.two_f_i_image).image(tbUrl, true, true, 200, R.drawable.ic_launcher, null, 0, 0);
		
		return arg1;
	}
	
	
}





@Override
public Loader<List<Item>> onCreateLoader(int arg0, Bundle arg1) {
	// TODO Auto-generated method stub
	asytask t=new asytask(getActivity(), arg1);
	System.out.println("onCreateLoader topic="+topic+" t==null"+(t==null));
	return t;
}

@Override
public void onLoadFinished(Loader<List<Item>> arg0, List<Item> arg1) {
	// TODO Auto-generated method stub
	
	//aq.find(R.id.progress).gone();
	//aq.find(R.id.two_layout_fragment_listview)
	//aq.find(R.id.two_layout_fragment_listview).adapter(new adapter(arg1)).itemClicked(this); 
	System.out.println("==================onLoadFinished topic="+topic);
	
	Toast.makeText(getActivity(), "size===="+arg1.size(), 1000).show();;
}

@Override
public void onLoaderReset(Loader<List<Item>> arg0) {
	// TODO Auto-generated method stub
	//System.out.println("onLoaderReset");
}
   
public void action(int i,String s){
	topic_cur=s;
	pos_cur=i;
//	System.out.println("==================action topic,topic_cur="+topic+","+topic_cur);
} 



 
}
